#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int dx[8] = { -1,-1,-1,0,0,1,1,1 };
    int dy[8] = { -1,0,1,-1,1,-1,0,1 };
    int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
        int ret = 1;
        queue<pair<int, int>> que;
        que.push({ 0,0 });
        int row = grid.size();
        int col = grid[0].size();
        if (row == 1 && col == 1 && grid[0][0] == 0)
            return 1;
        if (grid[0][0] == 1 || grid[row - 1][col - 1] == 1)
            return -1;

        vector<vector<bool>> check(row, vector<bool>(col));
        check[0][0] = 1;

        while (que.size())
        {
            int si = que.size();
            for (int i = 0; i < si; ++i)
            {
                int x1 = que.front().first;
                int y1 = que.front().second;
                que.pop();
                for (int x = 0; x < 8; ++x)
                {
                    int x2 = x1 + dx[x];
                    int y2 = y1 + dy[x];

                    if (x2 == row - 1 && y2 == col - 1)
                        return ret + 1;
                    if (x2 >= 0 && x2 < row && y2 >= 0 && y2 < col && check[x2][y2] == 0 && grid[x2][y2] == 0)
                    {
                        que.push({ x2,y2 });
                        check[x2][y2] = 1;
                    }
                }
            }

            ret++;
        }

        return -1;
    }
};